﻿#include "MysqlDao.h"

MysqlDao::MysqlDao()
{
	auto & cfg = ConfigMgr::Inst();
	const auto& host = cfg["Mysql"]["Host"];
	const auto& port = cfg["Mysql"]["Port"];
	const auto& pwd = cfg["Mysql"]["Password"];
	const auto& schema = cfg["Mysql"]["Schema"];
	const auto& user = cfg["Mysql"]["User"];
	pool_.reset(new MySqlPool(host+":"+port, user, pwd,schema, 5));
}

MysqlDao::~MysqlDao(){
	pool_->Close();
}


//获取该用户的文件元数据(分批)
QList<FileInfo> MysqlDao::GetFilesByUser(int user_id, int limit, int offset)
{
    QList<FileInfo> resultList;  // 存储查询结果的列表

    auto con = pool_->getConnection();
    if (!con) {
        qDebug() << "mysql connection failed";
        return resultList;
    }

    Defer defer([this, &con] { pool_->returnConnection(std::move(con)); });

    try {
        // 使用用户ID和上传时间的联合索引优化查询性能
        std::unique_ptr<sql::PreparedStatement> pstmt(
            con->_con->prepareStatement(
                "SELECT file_id, user_id, storage_path, upload_time, "
                "logical_name, process_type, file_hash "
                "FROM file_info "
                "WHERE user_id = ? "
                "ORDER BY upload_time DESC "
                "LIMIT ? OFFSET ?"
                )
            );

        // 绑定参数
        pstmt->setInt(1, user_id);      // 用户ID
        pstmt->setInt(2, limit);        // 每页记录数
        pstmt->setInt(3, offset);       // 偏移量（分页起始位置）

        // 执行查询
        std::unique_ptr<sql::ResultSet> res(pstmt->executeQuery());

        // 遍历结果集
        while (res->next()) {
            FileInfo fileInfo;
            fileInfo.fileId = res->getInt64("file_id");
            fileInfo.userId = res->getInt64("user_id");
            fileInfo.storagePath = QString::fromStdString(res->getString("storage_path"));

            // 处理日期时间转换
            std::string uploadTimeStr = res->getString("upload_time");
            fileInfo.uploadTime = QDateTime::fromString(
                QString::fromStdString(uploadTimeStr),
                "yyyy-MM-dd HH:mm:ss.zzz"  // 匹配datetime(6)格式
                );

            fileInfo.logicalName = QString::fromStdString(res->getString("logical_name"));
            fileInfo.processType = QString::fromStdString(res->getString("process_type"));
            fileInfo.fileHash = QString::fromStdString(res->getString("file_hash"));

            resultList.append(fileInfo);
        }

    }
    catch (sql::SQLException& e) {
        std::cerr << "SQLException in GetFilesByUser: " << e.what()
        << "\nError code: " << e.getErrorCode()
        << "\nSQLState: " << e.getSQLState() << std::endl;
    }
    return resultList;
}
